
importScripts('https://storage.googleapis.com/workbox-cdn/releases/7.3.0/workbox-sw.js');
const PRECACHE = 'precache-v1';
const RUNTIME = 'runtime';
// A list of local resources we always want to be cached.
const PRECACHE_URLS = [
  'index.html',
  './', // Alias for index.html
];

// The install handler takes care of precaching the resources we always need.
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(PRECACHE).then(cache => {
      console.log('Caching app shell');
      return cache.addAll(PRECACHE_URLS);
    })
  );
  console.log('Service worker installed');

});

// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', event => {
  const currentCaches = [PRECACHE, RUNTIME];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
    }).then(cachesToDelete => {
      return Promise.all(cachesToDelete.map(cacheToDelete => {
        return caches.delete(cacheToDelete);
      }));
    }).then(() => self.clients.claim())
  );
});

// The fetch handler serves responses for same-origin resources from a cache.
// If no response is found, it populates the runtime cache with the response
// from the network before returning it to the page.

// workbox.routing.registerRoute(
//   // Cache CSS files
//   /\.css$/,
//   new workbox.strategies.CacheFirst({
//     cacheName: 'css-cache',
//     plugins: [
//       new workbox.expiration.Plugin({
//         maxEntries: 30,
//       }),
//     ],
//   })
// );// Cache CSS files
workbox.routing.registerRoute(
  /\.css$/,
  new workbox.strategies.CacheFirst({
    cacheName: 'css-cache'
  })
);

workbox.routing.registerRoute(
  // Cache image files
  /\.(?:png|gif|jpg|jpeg|svg)$/,
  new workbox.strategies.CacheFirst({
    cacheName: 'image-cache'
  })
);

workbox.routing.registerRoute(
  // Cache JS files
  /\.js$/,
  new workbox.strategies.CacheFirst({
    cacheName: 'js-cache'
  })
);
  
  // JS 请求: 网络优先
workbox.routing.registerRoute(
  // Cache JS files
  new RegExp('.*/api.*'),
  new workbox.strategies.NetworkOnly()
);